package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.Permission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class PermissionServiceImpl implements PermissionService{

    @Autowired
    PermissionDao permissionDao;

    @Override
    public void add(Permission permission) {
        log.debug("service:{"+permission+"}");
        permissionDao.add(permission);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        log.debug("service:" + queryPageBean);
        //1. 开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //2. 条件查询
        Page<Permission> page = permissionDao.findByCondition(queryPageBean.getQueryString());
        log.debug("page{"+page+"}");
        //封装PageResult
        return new PageResult(page.getTotal(), page);
    }

    /**
     * 判断是否被角色数据所关联
     *  1. 如果被关联，则不删除，抛出异常，不能删除
     *  2. 如果没有关联，直接删除检查项
     * @param id
     */
    @Override
    public void delById(Integer id) {

        long count = permissionDao.findCountById(id);
        if(count > 0) {
            //说明被关联
            throw new BusinessRuntimeException("该权限数据被角色数据关联，不能删除！！");
        }else {
            permissionDao.delById(id);
        }
    }

    /**
     * 获取某一数据
     * @param id 数据ID
     * @return 对象
     */
    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    @Transactional
    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }

    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }
}
